//
//  LoginView.m
//  OASystem
//
//  Created by macos on 14-4-15.
//  Copyright (c) 2014年 macos. All rights reserved.
//

#import "LoginView.h"

@interface LoginView ()

@end

@implementation LoginView

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    nameField.text = USER_NAME;
    passWordField.text = USER_PASSWORD2;
    if(![USER_PASSWORD2 isEqualToString:@""])
    {
        [reminderPassWordButt setBackgroundImage:[UIImage imageNamed:@"login_checkbox_checked.png"] forState:UIControlStateNormal];
        remindePassWdFlag = 1;
    }
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    tipScr.contentSize =CGSizeMake(280, 100);
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"login_bg.png"]];
    
    //按钮的两种状态
    [loginButton setBackgroundImage:[UIImage imageNamed:@"login_btn_n.png"] forState:UIControlStateNormal];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"login_btn_p.png"] forState:UIControlStateHighlighted];
    
    
    //输入框编辑通知 如果是记住密码的用户 输入用户名即可自动填充密码
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldChanged)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nameField];
    
}
//输入用户名自动匹配密码
- (void)textFieldChanged
{
    [reminderPassWordButt setBackgroundImage:[UIImage imageNamed:@"login_checkbox_n.png"] forState:UIControlStateNormal];
    NSLog(@"tttyy----%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"USER_NAME"]);
    if ([nameField.text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"USER_NAME"]])
    {
        passWordField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PASSWORD2"];
    }
}

//记住密码操作
- (IBAction)remindePassWordAction:(UIButton *)sender
{
    if(remindePassWdFlag == 0)
    {
        [reminderPassWordButt setBackgroundImage:[UIImage imageNamed:@"login_checkbox_checked.png"] forState:UIControlStateNormal];
        remindePassWdFlag = 1;
        [[NSUserDefaults standardUserDefaults] setObject:nameField.text forKey:@"USER_NAME"];
        [[NSUserDefaults standardUserDefaults] setObject:passWordField.text forKey:@"USER_PASSWORD2"];
    }
    else
    {
        [reminderPassWordButt setBackgroundImage:[UIImage imageNamed:@"login_checkbox_n.png"] forState:UIControlStateNormal];
        remindePassWdFlag = 0;
        
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"USER_NAME"];
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"USER_PASSWORD2"];
    }
//    [[NSUserDefaults standardUserDefaults] setObject:passWordField.text forKey:@"USER_PASSWORD2"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//登录操作
- (IBAction)loginAction:(UIButton *)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self changeFrame:0];
    
    if(nameField.text.length == 0 || passWordField.text.length == 0)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"用户名或密码不能为空，请重新输入！"}];
    }
    else
    {
        NSLog(@"1----%@",nameField.text);
        NSLog(@"2----%@",passWordField.text);
//        [[NSUserDefaults standardUserDefaults] setObject:passWordField.text forKey:@"temp2"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
//        CocoaSecurityResult *result_sha1 = [CocoaSecurity sha1:passWordField.text];
//        [[SendHttpOperation shareSendHttpOperation] login:@"login.ashx"
//                                                    Useid:nameField.text
//                                                      Pwd:result_sha1.hex];
//        [SendHttpOperation shareSendHttpOperation].loginDelegate = self;
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSDictionary *tempDic = [[NSDictionary alloc] init];
            tempDic = [[SendHttpOperation shareSendHttpOperation] login_do:nameField.text passWord:passWordField.text];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
                if([[tempDic allKeys] containsObject:@"errcode"])
                {
                    if([[tempDic objectForKey:@"errcode"] isEqualToString:@"0"])
                    {
                        documentFlag = [[[tempDic objectForKey:@"info"] objectForKey:@"flag"] intValue];
                        
                        [[NSUserDefaults standardUserDefaults] setObject:nameField.text forKey:@"temp"];
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"用户登录成功获取用户信息！"}];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
                        CocoaSecurityResult *result_sha1 = [CocoaSecurity sha1:passWordField.text];
                        [[SendHttpOperation shareSendHttpOperation] getUserInfo:@"GetUserInfo.ashx"
                                                                          Useid:nameField.text
                                                                            Pwd:result_sha1.hex];
                        [SendHttpOperation shareSendHttpOperation].getUserInfoDelegate = self;
                    }
                    else
                       [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"用户验证失败，请重新尝试！"}];
                }
                else
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"网络请求数据失败，请重新尝试！"}];
            });
        });
    }
}

//登录返回数据回调函数
- (void)passLogin:(NSDictionary *)loginDic
{
    NSLog(@"over");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];

    if([[loginDic allKeys] containsObject:@"result"])
    {
        int flag = [[[loginDic objectForKey:@"result"] objectForKey:@"value"] intValue];
        
        
        switch (flag) {
            case 0:
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"用户名不存在，请重新输入！"}];
                break;
            case 1:
            {
                [[NSUserDefaults standardUserDefaults] setObject:nameField.text forKey:@"temp"];

                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"用户登录成功获取用户信息！"}];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
                CocoaSecurityResult *result_sha1 = [CocoaSecurity sha1:passWordField.text];
                [[SendHttpOperation shareSendHttpOperation] getUserInfo:@"GetUserInfo.ashx"
                                                                  Useid:nameField.text
                                                                    Pwd:result_sha1.hex];
                [SendHttpOperation shareSendHttpOperation].getUserInfoDelegate = self;
            }
                break;
            case 2:
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"用户已锁定，请重新输入！"}];
                break;
            case 3:
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"密码不正确，请重新输入！"}];
                break;
            default:
                break;
        }
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"网络获取数据失败，请重新尝试！"}];
    }
}

//获取用户信息回调
- (void)passgetUserInfo:(NSDictionary *)loginDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
    NSString *str = [NSString stringWithFormat:@"%@",[[[[[loginDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"] objectAtIndex:0] objectAtIndex:4]];
    NSString *idstr = [NSString stringWithFormat:@"%@",[[[[[loginDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"] objectAtIndex:0] objectAtIndex:0]];
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"USER_NICK_NAME"];
    [[NSUserDefaults standardUserDefaults] setObject:idstr forKey:@"USER_OWNER_GUDID"];
    
    //进入主界面
    MainView *instance = [[MainView alloc] init];
    instance.documentFlag = documentFlag;
    instance.nameStr = nameField.text;
    instance.passwordStr = passWordField.text;
    [self.navigationController pushViewController:instance animated:YES];
}

//触摸非编辑区域释放键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self changeFrame:0];
}

#pragma mark TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self changeFrame:1];
    
    if(textField == nameField)
    {
        nameField.borderStyle = UITextBorderStyleNone;
        passWordField.borderStyle = UITextBorderStyleLine;
        
        nameBack.hidden = NO;
        passWdBack.hidden = YES;
    }
    else
    {
        nameField.borderStyle = UITextBorderStyleLine;
        passWordField.borderStyle = UITextBorderStyleNone;
        passWdBack.hidden = NO;
        nameBack.hidden = YES;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self changeFrame:0];
    
    return YES;
}

#pragma mark 动态改变Frame
- (void)changeFrame:(int)flag
{
    passWdBack.hidden = YES;
    nameBack.hidden = YES;
    nameField.borderStyle = UITextBorderStyleLine;
    passWordField.borderStyle = UITextBorderStyleLine;
 
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES];
    if(1 == flag)
        self.view.frame = CGRectMake(0, -100+(MODEL5?88:0), 320, self.view.frame.size.height);
    else
        self.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height);
    [UIView commitAnimations];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
